<?php
/**
 * Controller ใช้ร่วมกันทั้ง ITS, Supplier และ Customer
 * หน้า display ใช้ร่วมกัน
 * หน้า view ใช้แยกกัน
 */
class MessagesController extends AppController {
    var $name = 'Messages';

    var $pageTitle = '';

    var $viewPath = 'messages';

    var $uses = array('MessageReceived', 'MessageSent', 'User', 'Customer', 'Supplier', 'CustomerSupplier', 'UserCoH');

    function beforeFilter() {
        parent::beforeFilter();
        $this->set('parentNav', 'messages');
    }

    /**
     * ลบ field ที่ไม่ได้ใช้ตอน search
     */
    function _clearSearchField() {
        unset($this->data['MessageSent']['customer_id']);
        unset($this->data['MessageSent']['supplier_id']);
        unset($this->data['MessageReceived']['customer_id']);
        unset($this->data['MessageReceived']['supplier_id']);
    }

    /**
     * หน้าหลักแสดงรายการ message ทั้งหน้า inbox และ sent
     * @param $page  หน้าที่จะแสดง 'inbox' || 'sent'
     */
    function display($page = 'inbox') {
        $this->_clearSearchField();
        $this->set('page', $page);

        if ($page == 'inbox') {
            $this->setAction('display_inbox');
        } else { // sent
            $this->setAction('display_sent');
        }
    }

    function display_inbox() {
        // ถ้ามาจากหน้า sent ให้ลบ session ที่เก็บเงื่อนไขการค้นหาออก
        if ($this->Session->read('Message.page') != 'inbox') {
            $this->Session->delete("{$this->name}.paging");
            $this->Session->write('Message.page', 'inbox');
        }
        parent::display('MessageReceived');

        $prefix = $this->Auth->user('prefix');
        $this->data['MessageReceived']['receiver'] = $prefix;
        if ($prefix == CUST_PREFIX) {
            $this->data['MessageReceived']['receiver_id'] = $this->Auth->user('customer_id');
        } elseif ($prefix == SUPPLIER_PREFIX) {
            $this->data['MessageReceived']['receiver_id'] = $this->Auth->user('supplier_id');
        }

//        $this->_checkBetweenSearch('MessageReceived', 'sent_time');

        $op = array(
                'receiver' => 'LIKE',
                'send_to' => 'LIKE',
                'sender_id' => '=',
                'sender' => '=',
                'subject' => 'LIKE',
        );
        $this->_paging('MessageReceived', $op);
    }

    function display_sent() {
        // ถ้ามาจากหน้า inbox ให้ลบ session ที่เก็บเงื่อนไขการค้นหาออก
        if ($this->Session->read('Message.page') != 'sent') {
            $this->Session->delete("{$this->name}.paging");
            $this->Session->write('Message.page', 'sent');
        }
        parent::display('MessageSent');

        $prefix = $this->Auth->user('prefix');
        $this->data['MessageSent']['sender'] = $prefix;
        if ($prefix == CUST_PREFIX) {
            $this->data['MessageSent']['sender_id'] = $this->Auth->user('customer_id');
        } elseif ($prefix == SUPPLIER_PREFIX) {
            $this->data['MessageSent']['sender_id'] = $this->Auth->user('supplier_id');
        }
        $this->_paging('MessageSent', 'LIKE');
    }

    /**
     *  หน้าแสดงข้อความ render view ตาม user type ที่เข้ามา
     */
    function view($id = null, $page = null) {
        $this->set('page', $page);
        $prefix = $this->Auth->user('prefix');

        if ($id != null) {
            // ดู message ที่ได้รับ
            if ($page == 'inbox') {
                $this->MessageReceived->contain('ToCustomer', 'ToSupplier', 'FromSupplier', 'FromCustomer', 'User');
                // User เปิดอ่านจดหมายของตัวเอง (โดยที่ไม่ใช้ from ITS มาแอบเปิดอ่าน เปลี่ยนสถาน is new
                if ($this->Session->read('Auth.User.Extend.from_its_user') == false) {
                    $this->MessageReceived->id = $id;
                    $this->MessageReceived->saveField('is_new', false);
                }

                $mr = $this->MessageReceived->findById($id);
                $this->data = $this->array_copy($mr, 'MessageReceived', 'Message');
                // ดู Message ที่ส่ง
            } elseif ($page == 'sent') {
                $this->MessageSent->contain('ToCustomer', 'ToSupplier', 'FromSupplier', 'FromCustomer', 'User');
                $mr = $this->MessageSent->findById($id);
                $this->data = $this->array_copy($mr, 'MessageSent', 'Message');
            }
            $this->set('mode' , 'edit');

        } elseif ($prefix == ITS_PREFIX) {
            $this->setAction('its_view', $id, $page);
        } elseif ($prefix == CUST_PREFIX) {
            $this->setAction('cust_view', $id, $page);
        } elseif ($prefix == SUPPLIER_PREFIX) {
            $this->setAction('sup_view', $id, $page);
        }
    }

    /**
     *  กำหนดค่า ตอบกลับจดหมาย
     */
    function reply($id) {
        $this->set('page', 'inbox');
        $prefix = $this->Auth->user('prefix');

        // แปลงข้อความที่ได้รับเป็นข้อความที่ต้องส่ง
        $this->MessageReceived->contain('ToCustomer', 'ToSupplier', 'FromSupplier', 'FromCustomer', 'User');
        $mr = $this->MessageReceived->findById($id);

        $sender = $mr['MessageReceived']['sender'];
        $this->data['MessageSent']['receiver'] = $sender;
        $this->data['MessageSent']['receiver_id'] = $mr['MessageReceived']['sender_id'];
        $this->data['MessageSent']['supplier_id'] = $mr['MessageReceived']['sender_id'];
        $this->data['MessageSent']['customer_id'] = $mr['MessageReceived']['sender_id'];
        $this->data['MessageSent']['send_to'] = $mr['User']['name'];
        $this->data['MessageSent']['subject'] = substr($mr['MessageReceived']['subject'], 0, 3) == 'RE:'? $mr['MessageReceived']['subject']: 'RE: ' .$mr['MessageReceived']['subject'];
        $body = '<br /><br /><br /><hr />';
        $body .= '<b>From : </b>' . $mr['User']['name'] . ' @ ';
        if ($sender == ITS_PREFIX) {
            $body .=  $this->requestAction('system_preferences/get/company_name');
        } elseif ($sender == CUST_PREFIX) {
            $body .= $mr['FromCustomer']['name'];
        } elseif ($sender == SUPPLIER_PREFIX) {
            $body .= $mr['FromSupplier']['name'];
        }
        $body .= '<br /><b>Attn.: </b>' . $mr['MessageReceived']['send_to'];
        $body .= '<br /><b>Subject : </b>' . $mr['MessageReceived']['subject'] . '<br /><br />';
        $this->data['MessageSent']['body'] = $body . $mr['MessageReceived']['body'];


        $this->set('mode' , 'edit');
        $this->set('reply_id' , $id);

        if ($prefix == ITS_PREFIX) {
            $this->setAction('its_view');
        } elseif ($prefix == CUST_PREFIX) {
            $this->setAction('cust_view');
        } elseif ($prefix == SUPPLIER_PREFIX) {
            $this->setAction('sup_view');
        }
    }

    /**
     * หน้าส่ง message ของ ITS
     * @param <type> $id
     */
    function its_view() {
        $this->set('suppliers', $this->Supplier->find('list', array('order' => 'Supplier.name')));
        // แสดงรายการเฉพาะที่ User นี้รับผิดชอบ
        $customers = $this->UserCoH->listCustomerOnHand($this->Auth->user('id'));
        $this->set('customers', $this->Customer->find('list', array('conditions' => array('id' => $customers), 'order' => 'Customer.name')));
        $this->set('mode' , 'add');
    }

    /**
     * หน้าส่ง message ของ Customer
     * @param <type> $id
     */
    function cust_view() {
        $this->_setSupplierByCustomer();
        $this->set('mode' , 'add');
    }

    /**
     * หน้าส่ง message ของ Supplier
     * @param <type> $id
     */
    function sup_view() {
        $this->_setCustomerBySupplier();
        $this->set('mode' , 'add');
    }

    function send() {
        $message_id = null;
        if (!empty($this->data)) {
            $this->MessageSent->query('BEGIN');
            // เช็คว่าผู้ส่งเป็นใคร ITS, Supplier หรือ Customer
            $prefix = $this->Auth->user('prefix');
            $this->data['MessageSent']['sender'] = $prefix;
            if ($prefix == CUST_PREFIX) {
                $this->data['MessageSent']['sender_id'] = $this->Auth->user('customer_id');
            } elseif ($prefix == SUPPLIER_PREFIX) {
                $this->data['MessageSent']['sender_id'] = $this->Auth->user('supplier_id');
            }

            // ถ้าผู้รับเป็น Customer หรือ Vendor แล้วไม่มีการเลือกผู้รับ
            if ($this->data['MessageSent']['receiver'] == CUST_PREFIX || $this->data['MessageSent']['receiver'] == SUPPLIER_PREFIX) {
                if (empty($this->data['MessageSent']['receiver_id'])) {
                    $this->MessageSent->validate['receiver_id'] = array('rule' => 'notEmpty', 'message' => 'Please select a receiver.');
                    $this->MessageReceived->validate['receiver_id'] = array('rule' => 'notEmpty', 'message' => 'Please select a receiver.');
                }
            }

            // ถ้าเป็นการ reply update message เก่าว่า reply แล้ว
            if (isset($this->data['reply_id'])) {
                $this->MessageReceived->id = $this->data['reply_id'];
                $this->MessageReceived->saveField('is_replied', true);
            }

            $this->data['MessageSent']['sent_time'] = date('Y-m-d H:i:s');
            $this->data['MessageSent']['user_id'] = $this->Session->read('Auth.User.id');
            // Copy MessageSent to MessageReceived
            $mr = array();
            $mr = $this->array_copy($this->data, 'MessageSent', 'MessageReceived');
            $mr['MessageReceived']['is_new'] = true;

            if($this->MessageSent->save($this->data) && $this->MessageReceived->save($mr)) {
                $this->MessageSent->query('COMMIT');
                $this->Session->setFlash("Send Message succesfull.", 'flash/ok');
                $message_id = $this->MessageSent->id;
            } else {
                $this->MessageSent->query('ROLLBACK');
                $this->Session->setFlash("Message send fail.", 'flash/fail');
            }
        }
        $this->setAction('view', $message_id, 'sent');
    }

    /** message
     * ลบ Customer ออกจาก Contract List ของ Supplier
     * @param <type> $id
     */
    function delete($id, $page) {
        $this->layout = 'ajax';
        $is_success = null;
        if ($page == 'inbox') {
            $this->MessageReceived->id = $id;
            $is_success = $this->MessageReceived->delete($id);
        } else { // sent
            $this->MessageSent->id = $id;
            $is_success = $this->MessageSent->delete($id);
        }

        if ($is_success) {
            $this->Session->setFlash("Delete message succesfull.", 'flash/ok');
        } else {
            $this->Session->setFlash("Can not delete this message.", 'flash/fail');
        }
        $this->setAction('display', $page);
    }

    function popup_search($page) {
        parent::popup_search();
        $this->set('popupWidth', 600);
        $this->set('action', 'display/' .$page);
        $prefix = $this->Auth->user('prefix');
        if ($prefix == ITS_PREFIX) {
            $this->setAction('its_popup_search', $page);
        } elseif ($prefix == CUST_PREFIX) {
            $this->setAction('cust_popup_search', $page);
        } elseif ($prefix == SUPPLIER_PREFIX) {
            $this->setAction('sup_popup_search', $page);
        }
    }

    function its_popup_search($page = null) {
        $this->set('suppliers', $this->Supplier->find('list', array('order' => 'Supplier.name')));
        // แสดงรายการเฉพาะที่ User นี้รับผิดชอบ
        $customers = $this->UserCoH->listCustomerOnHand($this->Auth->user('id'));
        $this->set('customers', $this->Customer->find('list', array('conditions' => array('id' => $customers), 'order' => 'Customer.name')));
        if ($page == 'inbox') {
            $this->render('its_popup_search');
        } else {
            $this->render('its_popup_search_sent');
        }
    }

    function cust_popup_search($page = null) {
        $this->_setSupplierByCustomer();
        if ($page == 'inbox') {
            $this->render('cust_popup_search');
        } else {
            $this->render('cust_popup_search_sent');
        }
    }

    function sup_popup_search($page = null) {
        $this->_setCustomerBySupplier();
        if ($page == 'inbox') {
            $this->render('sup_popup_search');
        } else {
            $this->render('sup_popup_search_sent');
        }
    }

    /**
     * จำนวน Message ใหม่ที่ได้รับที่ยังไม่ได้เปิดอ่าน
     */
    function new_message_count() {
        $prefix = $this->Auth->user('prefix');
        $conditions['MessageReceived.receiver'] = $prefix;
        if ($prefix == CUST_PREFIX) {
            $conditions['MessageReceived.receiver_id'] = $this->Auth->user('customer_id');
        } elseif ($prefix == SUPPLIER_PREFIX) {
            $conditions['MessageReceived.receiver_id'] = $this->Auth->user('supplier_id');
        }
        $conditions['MessageReceived.is_new'] = true;
        return $this->MessageReceived->find('count', array('conditions' => $conditions));
    }

    function _setSupplierByCustomer() {
        // Subquery ดึงรายการ Supplier ที่อยู่ใน Customer Contract list ของ Supplier นี้
        $conditionsSubQuery['CustomerSupplier.customer_id'] = $this->Auth->user('customer_id');
        $dbo = $this->CustomerSupplier->getDataSource();
        $subQuery = $dbo->buildStatement(
                array(
                'fields' => array('CustomerSupplier.supplier_id'),
                'table' => $dbo->fullTableName($this->CustomerSupplier),
                'alias' => 'CustomerSupplier',
                'conditions' => $conditionsSubQuery,
                'order' => null, 'limit' => null, 'group' => null,
                ),
                $this->CustomerSupplier
        );
        $subQuery = ' Supplier.id IN (' . $subQuery . ') ';
        $subQueryExpression = $dbo->expression($subQuery);
        $conditions[] = $subQueryExpression;

        $suppliers = $this->Supplier->find('list', array('conditions' => $conditions, 'order' => 'Supplier.name'));
        $this->set('suppliers' , $suppliers);
    }

    /*
    * Subquery ดึงรายการ Customer ที่อยู่ใน Customer Contract list ของ Supplier นี้
    */
    function _setCustomerBySupplier() {
        $conditionsSubQuery['CustomerSupplier.supplier_id'] = $this->Auth->user('supplier_id');
        $dbo = $this->CustomerSupplier->getDataSource();
        $subQuery = $dbo->buildStatement(
                array(
                'fields' => array('CustomerSupplier.customer_id'),
                'table' => $dbo->fullTableName($this->CustomerSupplier),
                'alias' => 'CustomerSupplier',
                'conditions' => $conditionsSubQuery,
                'order' => null,
                'limit' => null,
                'group' => null,
                ),
                $this->CustomerSupplier
        );
        $subQuery = ' Customer.id IN (' . $subQuery . ') ';
        $subQueryExpression = $dbo->expression($subQuery);
        $conditions[] = $subQueryExpression;
        $conditions[] = $subQueryExpression;
        // แสดงรายการเฉพาะที่ User นี้รับผิดชอบ
        $conditions['id'] = $this->UserCoH->listCustomerOnHand($this->Auth->user('id'));

        $customers = $this->Customer->find('list', array('conditions' => $conditions, 'order' => 'Customer.name'));
        $this->set('customers' , $customers);
    }

    function customer_user_list($customer_id) {

    }

    function supplier_user_list($supplier_id) {
        
    }
}
?>
